#include "communication_doctor.h"
#include "ui_communication_doctor.h"
#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlQuery>
communication_doctor::communication_doctor(int currentID, QString &role, QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
//    ui->setupUi(this);
//    this->currentID = currentID;
//    this->role = role;
//    ui->port->setText("8899");
//      qDebug()<<"AAAAAAAAAAAAAAAAAaaaaaAAAAAAAAaAaaaa";
//    setWindowTitle("河师大软件学院附属医院挂号处");
//    m_s=new QTcpServer(this);

//    db = QSqlDatabase::addDatabase("QSQLITE");
//    db.setDatabaseName(DATABASE_FILE_PATH); // 替换为实际的数据库文件名
//    if (!db.open()) {
//        QMessageBox::warning(this, "数据库错误", "无法打开数据库");
//    }


//    connect(m_s, &QTcpServer::newConnection,this,[=](){
//        m_tcp =m_s->nextPendingConnection();
//        m_status->setPixmap(QPixmap(":/OIP-C.jpg").scaled(20,20));

//        connect(m_tcp,&QTcpSocket::readyRead,this,[=](){
//            QByteArray data =m_tcp->readAll();
//            ui->record ->append("患者say:"+data);      //可将此预约信息data存往数据库

//            storeDataInDatabase(data);
//        });

//        connect(m_tcp,&QTcpSocket::disconnected,this,[=]()
//        {
//            m_tcp->close();
//            m_tcp->deleteLater();
//            m_status->setPixmap(QPixmap(":/OIP-C (1).jpg").scaled(20,20));
//        });

//    });

//    m_status=new QLabel;
//    m_status->setPixmap(QPixmap(":/OIP-C (1).jpg").scaled(20,20));
//    ui->statusbar->addWidget(new QLabel("连接状态:"));
//    ui ->statusbar->addWidget(m_status);

//    connect(ui->setlisten, &QPushButton::clicked, this, &communication_doctor::on_setlisten_clicked);
//    connect(ui->pushButton, &QPushButton::clicked, this, &communication_doctor::on_pushButton_clicked);
/*********************************************************************************/
    ui->setupUi(this);
    ui->port->setText("8899");
//    ui->ip->setText("127.0.0.1");
    setWindowTitle("医生沟通专用");
//    ui->setlisten->setDisabled(false);
//    ui->disconnect->setEnabled(false);
    m_tcp = new QTcpSocket(this);
    // 直接连接到服务器，硬编码 IP 地址
     m_tcp->connectToHost(QHostAddress("127.0.0.1"), ui->port->text().toUShort());

    connect(m_tcp, &QTcpSocket::readyRead, this, [=](){
        QByteArray data = m_tcp->readAll();
        ui->record->append("患者say: " + data);
    });

    connect(m_tcp, &QTcpSocket::disconnected, this, [=](){
        m_tcp->close();
        m_tcp->deleteLater();
        m_status->setPixmap(QPixmap(":/OIP-C (1).jpg").scaled(20, 20));
        ui->record->append("沟通服务结束");
    });

    connect(m_tcp, &QTcpSocket::connected, this, [=](){
        m_status->setPixmap(QPixmap(":/OIP-C.jpg").scaled(20, 20));
        ui->record->append("沟通服务开始");
//        ui->connect->setDisabled(true);
//        ui->disconnect->setEnabled(true);
    });

    m_status = new QLabel;
    m_status->setPixmap(QPixmap(":/OIP-C (1).jpg").scaled(20, 20));
    ui->statusbar->addWidget(new QLabel("连接状态:"));
    ui->statusbar->addWidget(m_status);
    /***********************************************************************************/

}

communication_doctor::~communication_doctor()
{
    delete ui;
}


//void communication_doctor::on_setlisten_clicked()
//{
//    unsigned short port =ui->port->text().toUShort();
//    m_s->listen(QHostAddress::Any,port);
//    ui->setlisten->setDisabled(true);
//}


void communication_doctor::on_sendMsg_clicked()
{
    QString msg=ui->msg ->toPlainText();
    m_tcp->write(msg.toUtf8());
    ui->record->append("医生say:"+msg);
}
////新增
//void communication_doctor::on_connect_clicked()
//{
//    QString ip = ui->ip->text();
//    unsigned short port = ui->port->text().toUShort();
//    m_tcp->connectToHost(QHostAddress(ip), port);
//}
////新增
//void communication_doctor::on_disconnect_clicked()
//{
//    m_tcp->close();
//    ui->connect->setDisabled(false);
//    ui->disconnect->setEnabled(false);
//}
void communication_doctor::storeDataInDatabase(const QByteArray &data)
{
    QSqlQuery query;
    query.prepare("INSERT INTO Communication (PatientID, DoctorID, Message, Date) VALUES (:patientID, :doctorID, :message, :date)");
    query.bindValue(":info", data);
    query.bindValue(":patientID", currentID);
    query.bindValue(":doctorID", currentID); // 假设医生和患者的ID相同
    query.bindValue(":message", data);
    query.bindValue(":date", QDateTime::currentDateTime().toString("yyyy-MM-dd"));

        if (query.exec()) {
        qDebug() << "患者预约信息已成功存储到数据库";
    } else {
        qDebug() << "存储患者信息到数据库时出错: " << query.lastError();
    }
}

void communication_doctor::displayDatabaseContents()
{
    QSqlQuery query;
    if (query.exec("SELECT * FROM Commnication"))
    {
        QString allMessages;
        while (query.next())
        {
            int messageID = query.value("MessageID").toInt();
            int patientID = query.value("PatientID").toInt();
            int doctorID = query.value("DoctorID").toInt();
            QByteArray messageInfo = query.value("Message").toByteArray();
            QString date = query.value("Date").toString();
            allMessages += QString("MessageID: %1, PatientID: %2, DoctorID: %3, Message: %4, Date: %5\n")
                    .arg(messageID)
                    .arg(patientID)
                    .arg(doctorID)
                    .arg(QString(messageInfo))
                    .arg(date);

            //            QByteArray appointmentInfo = query.value("appointment_info").toByteArray();
//            allAppointments += "预约信息: " + QString(appointmentInfo) + "\n";
        }

        if (!db.isOpen())
        {
            qDebug() << "数据库未打开，无法查询内容";
            return;
        }

        ui->textEdit->setText(allMessages);
    }
    else
    {
        qDebug() << "查询数据库内容出错: " << query.lastError();
    }
}

//void communication_doctor::on_pushButton_clicked()
//{
//    displayDatabaseContents();
//}
